﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DemoStock.Helper
{
    public class HttpInfoHelper
    {
		private static readonly string[] userAgentList = {
			"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
			"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
			"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
			"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
			"Mozilla/5.0 (Linux; Android 5.1.1; Nexus 6 Build/LYZ28E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Mobile Safari/537.36",
			"Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89;GameHelper",
			"Mozilla/5.0 (iPhone; CPU iPhone OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1",
			"Mozilla/5.0 (iPad; CPU OS 10_0 like Mac OS X) AppleWebKit/602.1.38 (KHTML, like Gecko) Version/10.0 Mobile/14A300 Safari/602.1",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:46.0) Gecko/20100101 Firefox/46.0",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
			"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4",
			"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:46.0) Gecko/20100101 Firefox/46.0",
			"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
			"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586"
		};

		public static string chooseUserAgent(string ua)
		{
			switch (ua)
			{
				case "mobile":
					return userAgentList[(int)Math.Floor(new Random().NextDouble() * 7)];
				case "pc":
					return userAgentList[(int)Math.Floor(new Random().NextDouble() * 5) + 8];
				default:
					return string.IsNullOrEmpty(ua) ? userAgentList[(int)Math.Floor(new Random().NextDouble() * userAgentList.Length)] : ua;
			}
		}
		/// <summary>
		/// 
		/// </summary>
		/// <param name="strUrl"></param>
		/// <returns></returns>
		public static async Task<string> GetResponseStringAsync(string strUrl,HttpMethod method, Dictionary<string, string> data)
		{
			HttpClient _httpClient = new HttpClient();
			HttpResponseMessage response;
			Dictionary<string, string> headers;
			Dictionary<string, string> datas;
			headers = new Dictionary<string, string>()
			{
				["User-Agent"] = chooseUserAgent("pc")
			};

			if (method == HttpMethod.Post)
			{
				headers["Content-Type"] = "application/x-www-form-urlencoded";
			}
			else if (method == HttpMethod.Get)
			{
				headers["Content-Type"] = "application/javascript; charset=GB18030";
			}
			datas = new Dictionary<string, string>();
			if (!(data is null))
			{
				foreach (KeyValuePair<string, string> item in data)
					datas.Add(item.Key, item.Value);
			}
			UriBuilder uriBuilder = new UriBuilder(strUrl);
			if (!(datas is null))
			{
				string query;

				query = datas.ToQueryString();
				if (!string.IsNullOrEmpty(query))
					if (string.IsNullOrEmpty(uriBuilder.Query))
						uriBuilder.Query = query;
					else
						uriBuilder.Query += "&" + query;
			}

			HttpRequestMessage request= new HttpRequestMessage(method, uriBuilder.Uri);
			
			if (!(headers is null))
				foreach (KeyValuePair<string, string> header in headers)
					request.Headers.TryAddWithoutValidation(header.Key, header.Value);
			response = await _httpClient.SendAsync(request);
			if (!response.IsSuccessStatusCode)
				throw new HttpRequestException();
			var encodeArr = System.Text.Encoding.GetEncodings();
			Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
			return await response.Content.ReadAsStringAsync();
			//using (var sr = new StreamReader(response.Content.ReadAsStreamAsync().Result, Encoding.GetEncoding("utf-8")))
			//{
			//	return await sr.ReadToEndAsync();
			//}
		}
	}

	internal static class HttpExtensions
	{
		public static string ToQueryString(this Dictionary<string, string> queries)
		{
			if (queries is null)
				throw new ArgumentNullException(nameof(queries));

			return string.Join("&", queries.Select(t => Uri.EscapeDataString(t.Key) + "=" + Uri.EscapeDataString(t.Value)));
		}
	}
}
